<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Crypt;
use DB;

class LoginController extends Controller
{
    //login
    public function login()
    {
    	return view('admin.login.login');
    }

    //dologin
    public function dologin(Request $request)
    {
    	// dd($request -> all());
    	$data = $request -> except('_token');

        $this ->validate($request,[
                'email' => 'required|email',
                'password' => 'required',
                
            ],[
                'password.required' => '密码不能为空',
                'email.required' =>'邮箱不能为空',
                'email.email' => '邮箱格式不正确', 
            ]);



        //判断是管理员还是商家
        if($data['auth'] == 0)
        {
            
            //验证码是否正确
            if($data['code'] == session('milkcaptcha'))
            {
                $res = DB::table('admins') -> where('email', $data['email']) -> first();
                // dd($res);
                if($res)
                {
                   $password = Crypt::decrypt($res -> password);
                // dd($password); 
               }else
               {
                    return back() -> with(['info' => '用户不存在']);
               }
                

                if($data['password'] == $password)
                {
                    session(['master' => $res]);
                    return redirect('/admin/index/index') -> with(['info' => '登录成功']);
                }

                // session(['master' => $res]);
                //     return redirect('/admin/index/index') -> with(['info' => '登录成功']);
            }else
            {
                return back() -> with(['info' => '验证码错误']);
            }
        }else
        {
            //验证码是否正确
            if($data['code'] == session('milkcaptcha'))
            {
                $res = DB::table('businesses') -> where('email', $data['email']) -> first();
                if($res)
                {
                   $password = Crypt::decrypt($res -> password);
                // dd($password); 
               }else
               {
                    return back() -> with(['info' => '用户不存在']);
               }
                

                if($data['password'] == $password)
                {
                    //存入session
                    session(['master' => $res]);
                    // $request -> flash();
                    return redirect('/business/index/index') -> with(['info' => '登录成功']);
                }


            }else
            {
                return back() -> with(['info' => '验证码错误']);
            }
        }

    	
    }

    //logout
    public function logout()
    {
    	session() -> flush();//清空session
    	return redirect('/admin/login');
    }

}
